package ali

import (
	"errors"
	"gitee.com/sansaniot/ssiot-core/msg/sms/model"
	time "github.com/alibabacloud-go/darabonba-time/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	console "github.com/alibabacloud-go/tea-console/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"strings"
)

type Sdk struct {
	Config *model.SMSConfig `json:"sms_config,omitempty"`
}

func (app *Sdk) SendSms(phone string, code string, data string) error {
	client, err := AliClient(app.Config)
	if err != nil {
		return err
	}

	sendReq := &dysmsapi.SendSmsRequest{
		PhoneNumbers:  &phone,
		SignName:      &app.Config.SignName,
		TemplateCode:  &code,
		TemplateParam: &data,
	}

	// 1.发送短信
	sendResp, err := client.SendSms(sendReq)
	if err != nil {
		return err
	}

	// 2. 请求响应
	resCode := sendResp.Body.Code
	if !tea.BoolValue(util.EqualString(resCode, tea.String("OK"))) {
		console.Warning(tea.String("错误信息: " + tea.StringValue(sendResp.Body.Message)))
		return errors.New("短信发送失败，请联系管理员。" + *sendResp.Body.Message)
	}
	return nil
}

// GetSendStatus 查询短信发送结果
// @phone 手机号码
// @sendResp 发送短信响应
func (app *Sdk) GetSendStatus(phone string, sendResp *dysmsapi.SendSmsResponse) error {
	client, err := AliClient(app.Config)
	if err != nil {
		return err
	}
	// 3. 查询结果（等待 10 秒后查询结果）
	bizId := sendResp.Body.BizId
	// 4. 查询结果
	phoneNums := strings.Split(phone, ",")
	for _, phoneNum := range phoneNums {
		queryReq := &dysmsapi.QuerySendDetailsRequest{
			PhoneNumber: util.AssertAsString(phoneNum),
			BizId:       bizId,
			SendDate:    time.Format(tea.String("yyyyMMdd")),
			PageSize:    tea.Int64(10),
			CurrentPage: tea.Int64(1),
		}
		queryResp, _err := client.QuerySendDetails(queryReq)
		if _err != nil {
			return _err
		}

		dtos := queryResp.Body.SmsSendDetailDTOs.SmsSendDetailDTO
		// 打印结果
		for _, dto := range dtos {
			if tea.BoolValue(util.EqualString(tea.String(tea.ToString(tea.Int64Value(dto.SendStatus))), tea.String("3"))) {
				console.Log(tea.String(tea.StringValue(dto.PhoneNum) + " 发送成功，接收时间: " + tea.StringValue(dto.ReceiveDate)))
			} else if tea.BoolValue(util.EqualString(tea.String(tea.ToString(tea.Int64Value(dto.SendStatus))), tea.String("2"))) {
				console.Log(tea.String(tea.StringValue(dto.PhoneNum) + " 发送失败"))
			} else {
				console.Log(tea.String(tea.StringValue(dto.PhoneNum) + " 正在发送中..."))
			}

		}
	}
	return err
}
